import config from '@/api/config.js';
import { goBack, showToast, toPage } from '@/utils/app.js';

import { TOKEN } from '@/utils/constants.js';
import { setItem, getItem, removeItem } from '@/utils/storage.js';

export function request(params) {
  const url = getUrl(params.url, params.query);
  const method = params.method;
  const data = params.data;

  let baseUrl = config.baseUrl;

  const header = {
    'Content-Type': 'application/json',
  };

  const token = getItem(TOKEN);
 if (token) {
    header['Authorization'] = 'Bearer ' + token;
  }

  if(params.header) {
    for(const key in params.header) {
      header[key] = params.header[key]
    }
  }

  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl + url,
      data: data,
      method,
      header,
      success: (res) => {
        if (res.statusCode === 200 || res.statusCode === 304) {
          const data = res.data;
          const code = data.code;
          const msg = data.msg;
          if (code === 401) {
            // 登录状态已过期
            showToast('登录已过期,请重新登录')
            uni.reLaunch({
              url:'/pages/user/wxLogin'
            })
          } else if (code === 500) {
            showToast(msg);
            return reject(data);
          } else if (code === 601) {
            showToast(msg);
            return reject(data);
          } else if (code !== 200) {
            showToast(msg);
            return reject(data);
          } else {
            return resolve(data);
          }
        } else {
          return reject({
            code: -1,
            msg: '数据异常，请稍后再试!',
          });
        }
      },
      fail: (err) => {
        let msg = 'request:fail';
        if (err && isString(err)) {
          msg = err;
        }
        if (err && isObject(err) && err.errMsg) {
          msg = err.errMsg;
        }
        let message = '';
        if (msg == 'request:fail timeout') {
          message = '请求超时';
        } else if (msg == 'request:fail') {
          message = '请求失败，请检查您的网络';
        } else if (msg == 'request:fail abort statusCode:-1') {
          message = '请求失败，请检查您的网络';
        } else {
          message = '请求失败';
        }
        return reject({
          code: -2,
          msg: message,
        });
      },
    });
  });
}

const getUrl = (requestUrl, requestParams) => {
  let url = requestUrl;
  if (requestParams) {
    const urlParams = [];
    for (var key in requestParams) {
      urlParams.push(key + '=' + requestParams[key]);
    }
    if (urlParams.length > 0) {
      url += '?' + urlParams.join('&');
    }
  }
  return url;
};

export const isObject = (val) => {
  return (
    Object.prototype.toString.call(val) === '[object Object]' && val !== null && val !== undefined
  );
};

export const isString = (val) => {
  return Object.prototype.toString.call(val) === '[object String]';
};
